package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.util.JDBC;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ResultTreeType;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据持久层，就是对数据进行mysql操作
 * 总结起来，就是对数据库进行CRUD操作
 * 增加，
 * 修改（修改密码，修改状态，修改性别，修改所有），
 * 删除，
 * 查询（查询所有，根据id查询）
 * 第二阶段，类于类之间的关系：泛化（继承，实现：）
 * 依赖（将一个类当作参数进行传递一般叫做依赖关系）
 * 关联（组合和聚合）
 */
public class NavImpl implements NavDao {

    public int add(NavModel navModel) {
        String sql = "INSERT INTO `nav` " +
                "(`title`, `href`," +
                " `is_show`, `create_time`" +
                " ) VALUES " +
                "('" + navModel.getTitle() + "', '" + navModel.getHref() + "', " +
                "'" + navModel.getEnable() + "', now() " +
                ");\n";
        return JDBC.getJdbc().update(sql);
    }

    public List<NavModel> getNavModelList(NavModel navModel) {
        List<NavModel> list = new ArrayList<>();
        int page = (navModel.getPage() - 1) * navModel.getLimit();
        String sql = "select * from nav limit " + page + ",10;";
        ResultSet resultSet = JDBC.getJdbc().query(sql);
//          知道有多少条数据，则用for循环
//            for (int i = 0; i < 10; i++) {
//        String str = "";
//        Reader read = null;
//        try {
//            read = new FileReader("");
//            int aa = 0;
//            while ((aa = read.read()) != -1) {
//                char cc = (char) aa;
//                Character character=cc;
//                str = str +character.toString()+""+cc+ " "+aa;
//            }
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

//            resultSet.next()如果还有下一条，则返回true，如果没有下一条，则返回false
//        解析结果集
        try {
            while (resultSet.next()) {
                NavModel model = new NavModel();
                model.setHref(resultSet.getString("href"));
                model.setName(resultSet.getString("title"));

                list.add(model);
            }
        } catch (Exception e) {

        } finally {
            JDBC.close();
        }
        return list;
    }

    public int update(NavModel navModel) {
//        String sql = "update nav set name='" + navModel.getName() + "',update_time=now() where id=" + navModel.getId();
        String sql = "UPDATE `nav` SET " +
                "`title` = '" + navModel.getTitle() + "', " +
                "`href` = '" + navModel.getHref() + "' " +
                " WHERE (`id` = '" + navModel.getId() + "');\n";
        return JDBC.getJdbc().update(sql);
    }

    @Override
    public int delete(NavModel navModel) {
        String sql = "delete from nav where id=" + navModel.getId();
        return JDBC.getJdbc().update(sql);
    }

    @Override
    public NavModel findById(NavModel navModel) {
        NavModel model = new NavModel();
        String sql = "select id,title,href,date_format(create_time,'%Y/%m/%d') create_time from nav where id=" + navModel.getId();
        ResultSet resultSet = JDBC.getJdbc().query(sql);
//        try {
//            while (resultSet.next()) {
//                model.setId(resultSet.getInt("id"));
//                model.setTitle(resultSet.getString("title"));
//                model.setHref(resultSet.getString("href"));
//                model.setCreateTime(resultSet.getString("create_time"));
//            }
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
        List<NavModel> list = getAll(resultSet);
//        if(list.size()>0){
//            return list.get(0);
//        }else {
//            return null;
//        }
//        ？左边的是条件语句，如果左边的是true，则返回的是冒号左边的，否则返回冒号右边的值
        return list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public List<NavModel> findAll(NavModel navModel) {
        int page = (navModel.getPage() - 1) * navModel.getLimit();
        String sql = "select * from nav ";
//        sql += " where title='" + navModel.getTitle() + "' ";
//        sql += " where title=? and href like concat('%',?,'%')";
//        ?可以理解为占位符
        sql += " limit " + page + ",10;";
        List<Object> parmList = new ArrayList<>();
//        有多少个？就应该有多少个参数，list就应该有多少个元素
//        parmList.add(navModel.getTitle());
//        parmList.add(navModel.getHref());
        ResultSet resultSet = JDBC.getJdbc().query(sql, parmList);
//        try {
//            while (resultSet.next()) {
//                NavModel model = new NavModel();
//                model.setId(resultSet.getInt("id"));
//                model.setTitle(resultSet.getString("title"));
//                model.setHref(resultSet.getString("href"));
//                model.setCreateTime(resultSet.getString("create_time"));
//
//                list.add(model);
//            }
//        } catch (Exception e) {
//
//        } finally {
//            JDBC.close();
//        }
        return getAll(resultSet);
    }

    /**
     * 将查询出来的结果集进行解析
     *
     * @param resultSet
     * @return
     */
    private List<NavModel> getAll(ResultSet resultSet) {
        List<NavModel> list = new ArrayList<>();
        try {
            while (resultSet.next()) {
                NavModel model = new NavModel();
                model.setId(resultSet.getInt("id"));
                model.setTitle(resultSet.getString("title"));
                model.setHref(resultSet.getString("href"));
                model.setCreateTime(resultSet.getString("create_time"));

                list.add(model);
            }
        } catch (Exception e) {

        } finally {
            JDBC.close();
        }
        return list;
    }

    @Override
    public int getCount(NavModel navModel) {
        String sql = "select count(*) count from nav";
        return JDBC.getJdbc().getCount(sql);
    }

    @Override
    public int updateEnable(NavModel navModel) {
        String sql = "update nav set enable=enable^1 where id=" + navModel.getId();
        return JDBC.getJdbc().update(sql);
    }

    @Override
    public int enable(NavModel navModel) {
        return 0;
    }
}
